<template>
	<el-dialog v-model="visible" append-to-body width="1000" fullscreen destroy-on-close :close-on-click-modal="false" @closed="$emit('closed')">
		<el-main class="page">
			<el-header style="padding: 0px">
				<div class="left-panel">
					<el-page-header :content="titleMap[mode]" @back="$emit('closed')"/>
				</div>
				<div class="right-panel">
					<el-form-item label="表名(英文)" prop="tableName">
						<template #label>
							<div style="margin-top:2px;font-size: 15px;">选择数据库</div>
						</template>
						<jd-select v-model="databaseId" :apiObj="$API.app.dbConn.getConnects" dataType="String" defaultFirst=true :apiProps="{label:'connName',value: 'connId'}" style="width: 100%;" placeholder="请选择..." @success="handleSelectSuccess" @change="changeDataBase"></jd-select>
					</el-form-item>
				</div>
			</el-header>
			<el-steps :active="active" finish-status="process" simple class="steps" style="width: 800px;margin: 35px auto;background: #FFF;">
				<el-step title="选择数据表"/>
				<el-step title="配置视图名"/>
				<el-step title="创建成功"/>
			</el-steps>
			<el-container v-if="active==0">
				<el-main>
					<el-row>
						<el-col :span="16">
							<div v-if="tableList.length==0">
								<el-empty description="请先选择一个数据库" :image-size="100" style="margin-top: 30px"></el-empty>
							</div>
							<div v-else>
								<el-transfer
									v-model="checkTables"
									:data="tableList"
									:render-content="renderFunc"
									:titles="['全部表', '已选择']"
									:format="{
										noChecked: '${total}张',
										hasChecked: '${checked}/${total}张'
									}"
									target-order="push"
									@change="handleChange"
									@right-check-change="rightCheckChange"
									style="width: 100%"
									key="id"
									>
									<span
										v-if="selectSourceFileArr.includes(option.key)"
										class="el-icon-edit field-transfer__icon"
									>AAA</span>
									<template #left-footer>
										<div style="padding: 10px;">数据表(Tables)</div>
									</template>
									<template #right-footer>
										<div style="padding: 10px;">视图表(Views)</div>
									</template>
								</el-transfer>
							</div>
						</el-col>
						<el-col :span="8">
							<div v-if="checkTables.length==0">
								<el-empty description="请先选择一张数据表" :image-size="100" style="margin-top: 30px"></el-empty>
							</div>
							<div v-else>
								<el-table :data="fieldList" :addBtn="false" placeholder="请先选择一张数据表">
									<el-table-column type="selection" width="55"> </el-table-column>
									<el-table-column prop="field" label="字段名"></el-table-column>
									<el-table-column prop="columnType" label="类型"></el-table-column>
								</el-table>
							</div>
						</el-col>
					</el-row>
				</el-main>
			</el-container>
			<el-row v-if="active==1">
				<el-col :span="24">
					<el-form :model="form" :rules="rules" :disabled="mode=='show'" ref="dialogForm" label-width="100px" size="large">
						<el-form-item label="表名(中文)" prop="tableComment">
							<el-input v-model="form.tableComment" @blur="getPinYin"  maxlength="20" placeholder="数据表的中文名称" />
						</el-form-item>
						<el-row>
							<el-col :span="14">
								<el-form-item label="表名(英文)" prop="tableName">
									<template #label>
										<div style="margin-top:2px">表名(英文)</div>
									</template>
									<el-input placeholder="数据表的英文名称" v-model="form.tableName" maxlength="50" suffix-icon="el-icon-scale-to-original">
										<template #prepend>app_</template>
									</el-input>
									<el-alert description="默认由系统自动生成拼音表名，如需修改请自行输入" type="warning" :closable="false" style="padding: 0px"/>
								</el-form-item>
							</el-col>
							<el-col :span="10">
								<el-form-item label="数据存储" prop="database">
									<jd-select v-model="form.database" :apiObj="$API.app.dbConn.getConnects" dataType="String" defaultFirst=true :apiProps="{label:'connName',value: 'connId'}" style="width: 100%;" placeholder="请选择..." disabled></jd-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-form-item label="表的说明" prop="remark">
							<el-input v-model="form.remark" maxlength="500" type="textarea" rows="5" show-word-limit placeholder="该数据表的说明文字，方便后期管理维护" />
						</el-form-item>
					</el-form>
				</el-col>
			</el-row>
			<el-row v-if="active==2" style="justify-content: center">
				<el-result
					icon="success"
					title="恭喜，应用创建成功"
					sub-title="下面请尽情发挥您的聪明大脑，开启您的开发之旅吧。"
				>
					<template #extra>
						<!-- <el-button>视频教程</el-button> -->
						<el-button>帮助手册</el-button>
						<el-button type="primary" @click="designApp">开发中心</el-button>
					</template>
				</el-result>
			</el-row>
			<el-row style="margin-top: 35px; justify-content: right;">
				<el-button :disabled="active <= 0" @click="handlePrevStep" v-if="active == 1">上一步</el-button>
				<el-button :disabled="active >= 1" @click="handleNextStep" v-if="active <= 0">下一步</el-button>
				<el-button type="primary" :loading="btnLoading" :disabled="active < 1" @click="createModel()" v-if="active == 1">保 存</el-button>
			</el-row>
		</el-main>
	</el-dialog>
</template>

<script>
	export default {
		emits: ['success', 'closed'],
		props: {

		},
		data() {
			return {
				leftValue: [],
				rightValue: [],
				// 渲染表名称
				renderFunc(h, option) {
					return h('span', null, option.label)
				},
				mode: "add",
				titleMap: {
					add: '创建视图',
					edit: '编辑视图',
					show: '查看'
				},
				visible: false,
				active: 0,
				//表单数据
				form: {
					tableId: "",
					tableName: "",
					tableComment: "",
					// TODO 当前APPID为固定值
					appId:23032316000942
				},
				//验证规则
				rules: {
					tableName:[
						{required: true, message: ''}
					],
					tableComment:[
						{required: true, message: ''}
					],
				},
				options: [
					{ label: '字符串', value: 'varchar' },
					{ label: '整型', value: 'int' },
					{ label: '日期时间', value: 'datetime' },
					{ label: '浮点', value: 'decimal' },
					{ label: '长整型', value: 'bigint' },
					{ label: '文本', value: 'longtext' }
				],
				databaseId: undefined,
				tableList: [],
				checkTables: [],
				fieldList: []
			}
		},
		mounted() {

		},
		watch: {
			databaseId: function(val){
				this.databaseId = val;
				this.getTableList(val)
			}
		},
		methods: {
			// 已选择框
			rightCheckChange(value){
				console.log(value,'xuanz')
			},
			handleChange(value, direction, movedKeys) {
				console.log(value, direction, movedKeys)
				console.log('this.leftValue',this.checkTables)
			},
			// 设置默认值
			handleSelectSuccess(val){
				this.databaseId = val;
				this.$nextTick(()=>{
					this.getTableList(val);
				})
			},
			//显示
			open(mode='add'){
				this.mode = mode;
				this.visible = true;
				this.requestParams = [];
				return this
			},
			// 获取应用拼音
			async getPinYin(){
				if (this.form.tableComment == ""){
					return;
				}
				var res = await this.$API.app.appStore.getPhonetic.get(this.form.tableComment)
				if (res.code == 200){
					this.form.tableName = res.data;
				}
			},
			handlePrevStep(){
				this.active -= 1;
      			this.$refs.dialogForm.clearValidate();
			},
			handleNextStep(){
				this.$refs.dialogForm.validate((valid) => {
					if (valid) {
						if (this.active < 1){
							this.active += 1;
						}
					}
				});
			},
			// 改变数据库
			changeDataBase(){
				this.getTableList(this.databaseId)
			},
			// 获取所有数据表
			async getTableList(id){
				let param={appId:this.form.appId,connectId:id}
				const data = [];
				var res = await this.$API.app.model.userModes.get(param);
				if (res.code == 200){
					res.data.map((item)=>{
						data.push({
							key: item.id,
							label: item.tableName
						});
					})
					this.tableList = data;
				}
			},
			// 获取所有字段
			async getTableInfo(){
				var res = await this.$API.app.dbConn.getFields.get(this.databaseId, 'app_qjyy_iwbbxj_1678159056220');
				if (res.code == 200){
					this.fieldList = res.data;
				}
			},
			// 设置主键
			changeKey(val, row) {
				row.allowNull = row.allowNull
				row.dataType = row.dataType
				row.dataLength = row.dataLength
				if (!val) return
				for (let i = 0; i < this.form.list.length; i++) {
					if (row.field != this.form.list[i].field) {
						this.$set(this.form.list[i], 'primaryKey', 0)
					}
				}
			},
			// 创建模型
			createModel(){
				this.$refs.dialogForm.validate(async (valid) => {
					if (valid) {
						// if (Array.isArray(this.form.deptId)){
						// 	var depts = this.form.deptId;
						// 	this.form.deptId = depts[depts.length - 1]
						// }

						// this.btnLoading = true;
						// var res = {};
						// res = await this.$API.app.appStore.addApp.post(this.form);
						// if(res.code == 200){
						// 	this.$emit('success', this.form, this.mode)
						// 	this.btnLoading = false;
						// 	this.active = 2;
						// }else{
						// 	this.$alert(res.msg, "提示", {type: 'error'})
						// }
					}
				})
			},
		}
	}
</script>

<style>
.el-dialog__body{
	padding: 20px;
	padding-right: 30px;
}
.steps{
	margin-bottom: 30px;
}
.el-collapse-item__header{
	font-weight: bolder;
	font-size: 16px;
	margin-top: 10px;
}
.el-transfer-panel{
	width: 300px;
}
</style>
